package is.model.dao;

import is.interfaces.Dao;
import is.model.bean.Department;
import is.model.dao.search.DepartmentSearch;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;

/**
 *
 * @author aspr0
 */
public class DepartmentDao extends AbstractDao<Department> implements Dao<Department>
{
    @Override
    public Integer create() throws SQLException
    {
        String query = "insert into %s %s";
        query = String.format(query, initialBean.getTableName(), genQmarksBycomma(initialBean));

        PreparedStatement statement = connection.prepareStatement(query);
        Integer parameterN = 1;

        statement.setString(parameterN++, initialBean.getName());

        Integer parentId = initialBean.getParentId();
        if (parentId != null)
        {
            statement.setInt(parameterN++, parentId);
        }

        Integer bossId = initialBean.getBossId();
        if (bossId != null)
        {
            statement.setInt(parameterN++, bossId);
        }

        statement.setInt(parameterN++, initialBean.getRegionId());

        statement.execute();
        return statement.getUpdateCount();
    }

    @Override
    public List<Department> search(Boolean strict) throws SQLException
    {
        return DepartmentSearch.search(strict, initialBean, connection);
    }

    @Override
    public Integer update() throws SQLException
    {
        String query = "update %s set %s where id = ? limit 1";

        query = String.format(query, initialBean.getTableName(), genQmarksByeqsign(initialBean));

        PreparedStatement statement = connection.prepareStatement(query);

        Integer parameterN = 1;

        statement.setString(parameterN++, initialBean.getName());

        Integer parentId = initialBean.getParentId();
        if (parentId != null)
        {
            statement.setInt(parameterN++, parentId);
        }

        Integer bossId = initialBean.getBossId();
        if (bossId != null)
        {
            statement.setInt(parameterN++, bossId);
        }

        statement.setInt(parameterN++, initialBean.getRegionId());
        statement.setInt(parameterN++, initialBean.getId());

        statement.execute();

        return statement.getUpdateCount();
    }
}
